{% extends "base.html" %}

{% block title %}医护端 - 康复预测系统{% endblock %}

{% block sidebar %}
<nav class="col-md-3 col-lg-2 d-md-block bg-light sidebar collapse">
    <div class="position-sticky pt-3">
        <ul class="nav flex-column">
            <li class="nav-item">
                <a class="nav-link active" href="#dashboard">
                    <i class="fas fa-tachometer-alt me-2"></i>控制面板
                </a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="#patients">
                    <i class="fas fa-users me-2"></i>患者管理
                </a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="#predictions">
                    <i class="fas fa-chart-bar me-2"></i>康复预测
                </a>
            </li>
            <li class="nav-item">
                <a class="nav-link" href="#analytics">
                    <i class="fas fa-chart-pie me-2"></i>数据分析
                </a>
            </li>
        </ul>
    </div>
</nav>
{% endblock %}

{% block content %}
<div id="dashboard">
    <div class="d-flex justify-content-between flex-wrap flex-md-nowrap align-items-center pt-3 pb-2 mb-3 border-bottom">
        <h1 class="h2">医护控制面板</h1>
        <div class="btn-toolbar mb-2 mb-md-0">
            <button class="btn btn-sm btn-outline-primary" onclick="addNewPatient()">
                <i class="fas fa-plus me-1"></i>新增患者
            </button>
        </div>
    </div>

    <!-- 统计卡片 -->
    <div class="row">
        <div class="col-xl-3 col-md-6 mb-4">
            <div class="card border-left-primary shadow h-100 py-2">
                <div class="card-body">
                    <div class="row no-gutters align-items-center">
                        <div class="col mr-2">
                            <div class="text-xs font-weight-bold text-primary text-uppercase mb-1">
                                总患者数
                            </div>
                            <div class="h5 mb-0 font-weight-bold text-gray-800" id="totalPatients">0</div>
                        </div>
                        <div class="col-auto">
                            <i class="fas fa-users fa-2x text-gray-300"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="col-xl-3 col-md-6 mb-4">
            <div class="card border-left-success shadow h-100 py-2">
                <div class="card-body">
                    <div class="row no-gutters align-items-center">
                        <div class="col mr-2">
                            <div class="text-xs font-weight-bold text-success text-uppercase mb-1">
                                今日新增
                            </div>
                            <div class="h5 mb-0 font-weight-bold text-gray-800" id="todayNew">0</div>
                        </div>
                        <div class="col-auto">
                            <i class="fas fa-user-plus fa-2x text-gray-300"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="col-xl-3 col-md-6 mb-4">
            <div class="card border-left-info shadow h-100 py-2">
                <div class="card-body">
                    <div class="row no-gutters align-items-center">
                        <div class="col mr-2">
                            <div class="text-xs font-weight-bold text-info text-uppercase mb-1">
                                高风险患者
                            </div>
                            <div class="h5 mb-0 font-weight-bold text-gray-800" id="highRiskPatients">0</div>
                        </div>
                        <div class="col-auto">
                            <i class="fas fa-exclamation-triangle fa-2x text-gray-300"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <div class="col-xl-3 col-md-6 mb-4">
            <div class="card border-left-warning shadow h-100 py-2">
                <div class="card-body">
                    <div class="row no-gutters align-items-center">
                        <div class="col mr-2">
                            <div class="text-xs font-weight-bold text-warning text-uppercase mb-1">
                                平均康复周期
                            </div>
                            <div class="h5 mb-0 font-weight-bold text-gray-800" id="avgRecoveryDays">0天</div>
                        </div>
                        <div class="col-auto">
                            <i class="fas fa-calendar-alt fa-2x text-gray-300"></i>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

    <!-- 患者列表 -->
    <div class="card">
        <div class="card-header">
            <h5 class="card-title mb-0">患者列表</h5>
        </div>
        <div class="card-body">
            <div class="table-responsive">
                <table class="table table-hover" id="patientsTable">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>姓名</th>
                            <th>年龄</th>
                            <th>损伤类型</th>
                            <th>严重程度</th>
                            <th>风险等级</th>
                            <th>预计康复天数</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody id="patientsTableBody">
                        <!-- 动态填充 -->
                    </tbody>
                </table>
            </div>
        </div>
    </div>
</div>

<!-- 新增患者模态框 -->
<div class="modal fade" id="addPatientModal" tabindex="-1">
    <div class="modal-dialog modal-lg">
        <div class="modal-content">
            <div class="modal-header">
                <h5 class="modal-title">新增患者</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
            </div>
            <div class="modal-body">
                <form id="patientForm">
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label class="form-label">姓名</label>
                                <input type="text" class="form-control" name="name" required>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label class="form-label">年龄</label>
                                <input type="number" class="form-control" name="age" min="18" max="100" required>
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label class="form-label">性别</label>
                                <select class="form-select" name="gender" required>
                                    <option value="1">男</option>
                                    <option value="0">女</option>
                                </select>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label class="form-label">损伤类型</label>
                                <select class="form-select" name="injury_type" required>
                                    <option value="骨折">骨折</option>
                                    <option value="软组织损伤">软组织损伤</option>
                                    <option value="关节问题">关节问题</option>
                                    <option value="神经损伤">神经损伤</option>
                                </select>
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label class="form-label">损伤严重程度 (1-10)</label>
                                <input type="number" class="form-control" name="injury_severity" min="1" max="10" required>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label class="form-label">初始活动能力 (0-100)</label>
                                <input type="number" class="form-control" name="initial_mobility" min="0" max="100" required>
                            </div>
                        </div>
                    </div>
                    <div class="row">
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label class="form-label">疼痛程度 (1-10)</label>
                                <input type="number" class="form-control" name="pain_level" min="1" max="10" required>
                            </div>
                        </div>
                        <div class="col-md-6">
                            <div class="mb-3">
                                <label class="form-label">预计依从率 (0.5-1.0)</label>
                                <input type="number" class="form-control" name="compliance_rate" min="0.5" max="1.0" step="0.1" required>
                            </div>
                        </div>
                    </div>
                    <div class="mb-3">
                        <label class="form-label">联系方式</label>
                        <input type="text" class="form-control" name="contact" required>
                    </div>
                </form>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">取消</button>
                <button type="button" class="btn btn-primary" onclick="submitPatientForm()">保存并预测</button>
            </div>
        </div>
    </div>
</div>
{% endblock %}

{% block scripts %}
<script>
// 页面加载时获取患者数据
document.addEventListener('DOMContentLoaded', function() {
    loadPatients();
});

// 加载患者列表
function loadPatients() {
    fetch('/api/patients')
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                updatePatientsTable(data.patients);
                updateStatistics(data.patients);
            }
        });
}

// 更新患者表格
function updatePatientsTable(patients) {
    const tbody = document.getElementById('patientsTableBody');
    tbody.innerHTML = '';
    
    patients.forEach(patient => {
        // 为每个患者进行预测
        const predictionData = {
            age: patient.age,
            gender: patient.gender,
            injury_type: patient.injury_type === '骨折' ? 0 : 
                        patient.injury_type === '软组织损伤' ? 1 :
                        patient.injury_type === '关节问题' ? 2 : 3,
            injury_severity: patient.injury_severity,
            treatment_type: 1, // 默认物理治疗
            compliance_rate: patient.compliance_rate || 0.8,
            initial_mobility: patient.initial_mobility,
            pain_level: patient.pain_level
        };
        
        fetch('/api/predict', {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            body: JSON.stringify(predictionData)
        })
        .then(response => response.json())
        .then(prediction => {
            if (prediction.success) {
                const row = tbody.insertRow();
                row.innerHTML = `
                    <td>${patient.id}</td>
                    <td>${patient.name}</td>
                    <td>${patient.age}</td>
                    <td>${patient.injury_type}</td>
                    <td>${patient.injury_severity}</td>
                    <td><span class="badge risk-${prediction.prediction.risk_level === '高风险' ? 'high' : 
                                              prediction.prediction.risk_level === '中风险' ? 'medium' : 'low'}">
                        ${prediction.prediction.risk_level}
                    </span></td>
                    <td>${prediction.prediction.predicted_days}天</td>
                    <td>
                        <button class="btn btn-sm btn-info" onclick="viewPatient(${patient.id})">查看</button>
                        <button class="btn btn-sm btn-warning" onclick="addRecord(${patient.id})">记录</button>
                    </td>
                `;
            }
        });
    });
}

// 更新统计信息
function updateStatistics(patients) {
    document.getElementById('totalPatients').textContent = patients.length;
    document.getElementById('todayNew').textContent = patients.filter(p => 
        p.registration_date === new Date().toISOString().split('T')[0]).length;
    
    // 这里可以添加更多统计逻辑
}

// 打开新增患者模态框
function addNewPatient() {
    const modal = new bootstrap.Modal(document.getElementById('addPatientModal'));
    modal.show();
}

// 提交患者表单
function submitPatientForm() {
    const form = document.getElementById('patientForm');
    const formData = new FormData(form);
    const patientData = Object.fromEntries(formData.entries());
    
    // 转换数据类型
    patientData.age = parseInt(patientData.age);
    patientData.injury_severity = parseInt(patientData.injury_severity);
    patientData.initial_mobility = parseInt(patientData.initial_mobility);
    patientData.pain_level = parseInt(patientData.pain_level);
    patientData.compliance_rate = parseFloat(patientData.compliance_rate);
    patientData.gender = parseInt(patientData.gender);
    patientData.assigned_doctor = 1; // 默认分配给当前医生
    
    fetch('/api/patient/add', {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        body: JSON.stringify(patientData)
    })
    .then(response => response.json())
    .then(data => {
        if (data.success) {
            bootstrap.Modal.getInstance(document.getElementById('addPatientModal')).hide();
            form.reset();
            loadPatients(); // 重新加载患者列表
            showAlert('患者添加成功！', 'success');
        } else {
            showAlert('添加失败：' + data.error, 'danger');
        }
    });
}

// 查看患者详情
function viewPatient(patientId) {
    window.location.href = `/patient_detail.html?id=${patientId}`;
}

// 添加康复记录
function addRecord(patientId) {
    // 实现添加记录逻辑
    alert(`为患者 ${patientId} 添加康复记录`);
}

// 显示提示信息
function showAlert(message, type) {
    const alertDiv = document.createElement('div');
    alertDiv.className = `alert alert-${type} alert-dismissible fade show`;
    alertDiv.innerHTML = `
        ${message}
        <button type="button" class="btn-close" data-bs-dismiss="alert"></button>
    `;
    document.querySelector('.main-content').prepend(alertDiv);
    setTimeout(() => alertDiv.remove(), 3000);
}
</script>
{% endblock %}